package models

import (
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

type TAnswer struct {
	Id               int       `orm:"column(id);auto"`
	Creattime        time.Time `orm:"column(creattime);" description:"姓名"`
	Chat             string    `orm:"column(chat);size(245);null" description:"密码"`
	Analysis         string    `orm:"column(analysis);size(245);null" description:"密码"`
	AskSN            string    `orm:"column(ask_sn);size(245);null" description:"密码"`
	AskName          string    `orm:"column(ask_name);size(245);null" description:"密码"`
	AnswerSN         string    `orm:"column(answer_sn);null" description:"密码"`
	QuestionTemplate string    `orm:"column(question_template);null" description:"密码"`
	Kind             int8      `orm:"column(kind);null" description:"0 普通访谈，1 出国访谈"`
}

func (t *TAnswer) TableName() string {
	return "t_answer"
}

func init() {

	orm.RegisterModel(new(TAnswer))
}

func AddTAnswer(answer *TAnswer) (err error) {
	o := orm.NewOrm()
	_, err = o.Insert(answer)
	if err != nil {
		return
	}
	updateStr := fmt.Sprintf(`UPDATE  t_user  SET last_fill_answer_time = '%s',
	 last_fill_answer_kind = '%d',last_fill_answer_template='%s' WHERE  sn = '%s' `,
		answer.Creattime.Format("2006-01-02 15:04:05"), answer.Kind, answer.QuestionTemplate, answer.AnswerSN)
	_, err = o.Raw(updateStr).Exec()
	return
}

// QueryUserAnswer retrieves all TAnswer matches certain condition. Returns empty list if
// no records exist
func QueryUserAnswerList(sn string) (l []*TAnswer, err error) {

	o := orm.NewOrm()
	// sql := fmt.Sprintf("select id,creattime from %s where answer_sn='%s' order by id desc", new(TAnswer).TableName(), sn)
	qs := o.QueryTable(new(TAnswer))
	qs = qs.Filter("answer_sn", sn)
	qs.OrderBy("-id")
	_, err = qs.All(&l)
	if err != nil {
		return
	}

	return
}

func QueryUserAnswerItem(id int) (l *TAnswer, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TAnswer))
	qs = qs.Filter("id", id)
	if err = qs.One(l); err == nil {
		return l, nil
	}
	return nil, err
}

type QuestionAnswer struct {
	Question string
	Answer   string
}
